const db = require('../db/index.js')

const createTableSql = (friendsTable) => {
    return `
    CREATE TABLE ${friendsTable} (
        id INT AUTO_INCREMENT PRIMARY KEY,
        friend_uid INT NOT NULL UNIQUE,
        chat_history_table VARCHAR(255), 
        status INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
}

// 添加好友到数据库
const addFriendToDB = async (uid, friendUid) => {
    const friendsTable = `friends_table_${uid}`
    try {
        //检查好友表是否存在
        let exists = await db.checkTableExists(friendsTable)
        if (exists) {
            //表存在
            //检查是否已经是好友
            const checkSql = `select * from ${friendsTable} where friend_uid=?`
            let [results] = await db.query(checkSql, [friendUid])
            if (results.length > 0) {
                return 2
            }
        } else {
            //表不存在
            //创建表
            await db.query(createTableSql(friendsTable))
        }
        //添加好友
        const sql = `insert into ${friendsTable} (friend_uid) values (?)`
        const [results] = await db.query(sql, [friendUid])
        if (results.affectedRows !== 1) {
            return 30
        }
        return 0

    } catch (err) {
        console.log('Error: addFriendToDB-> ', err.message)
        throw err
    }
}

// 获取所有好友uid
const getFriendsUid = async (req, res) => {
    const uid = req.user.uid
    const friendsTable = `friends_table_${uid}`
    const friendsUidList = [] //表不存在直接返回空数组
    try {
        if (await db.checkTableExists(friendsTable)) {
            //表存在
            const sqlStr = `select friend_uid,status from ${friendsTable}`
            const [results] = await db.query(sqlStr)
            results.forEach(x => {
                if (x.status === 0) {
                    friendsUidList.push(x.friend_uid)
                }
            })
        }
        return res.send({
            code: 0,
            msg: '获取所有好友uid成功',
            data: {
                uid,
                friends: friendsUidList
            }
        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: getFriendsUid-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }

}

// 添加好友
const addFriend = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.friendUid) {
        return res.cc('添加的好友uid不能为空', 10)
    }
    const uid = req.user.uid, friendUid = req.body.friendUid
    if (uid === friendUid) {
        return res.cc('目标用户不能是自己', 3)
    }
    try {
        // 检查目标用户
        const searchSql = 'select uid,username,status from users where uid=?'
        let [results] = await db.query(searchSql, [friendUid])
        if (results.length <= 0 || !results[0].status) {
            return res.cc('目标用户不存在', 1)
        }
        if (results.length !== 1) {
            return res.cc('目标用户数据读取失败', 30)
        }
        // 添加到数据库
        // 返回值信息
        const resultInfo = {
            2: '目标用户已经是好友',
            30: '添加失败, 请稍后再试'
        }
        results = await addFriendToDB(uid, friendUid)
        if (results) {
            return res.cc(resultInfo[results], results)
        }
        results = await addFriendToDB(friendUid, uid)
        if (results) {
            return res.cc(resultInfo[results], results)
        }
        return res.send({
            code: 0,
            msg: '添加好友成功',
            data: {
                uid,
                friendUid
            }
        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: addFriend-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}


// 从数据库删除好友
const removeFriendFromDB = async (uid, friendUid) => {
    try {
        const friendsTable = `friends_table_${uid}`
        if (await db.checkTableExists(friendsTable)) {
            //表存在
            //检查是否已经是好友
            let sqlStr = `select * from ${friendsTable} where friend_uid=?`
            let [results] = await db.query(sqlStr, [friendUid])
            if (results.length <= 0) {
                return 1
            }
            //是好友就删除
            sqlStr = `delete from ${friendsTable} where friend_uid=?`
                ;[results] = await db.query(sqlStr, [friendUid])
            if (results.affectedRows !== 1) {
                return 30
            }
            return 0


        } else {
            //表不存在
            return 1
        }
    } catch (err) {
        console.log('Error: removeFriendFromDB-> ', err.message)
        throw err
    }

}


// 删除好友
const removeFriend = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.friendUid) {
        return res.cc('删除的好友uid不能为空', 10)
    }
    const uid = req.user.uid, friendUid = req.body.friendUid

    try {
        // 从数据库中删除
        let results1 = await removeFriendFromDB(uid, friendUid)
        let results2 = await removeFriendFromDB(friendUid, uid)
        if (results1 === 1 || results2 === 1) {
            return res.cc('目标用户不在好友列表内', 1)
        }
        if (results1 === 30 || results2 === 30) {
            return res.cc('删除失败, 请稍后再试', 30)
        }

        return res.send({
            code: 0,
            msg: '删除好友成功',
            data: {
                uid,
                friendUid
            }
        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: removeFriend-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}
module.exports = {
    getFriendsUid,
    addFriend,
    removeFriend
}